package category

import (
	"context"
	"errors"
	"fmt"
	"github.com/google/uuid"
	"github.com/spf13/cast"
	"gorm.io/gorm"
	"insighttracking/common/enum"
	"insighttracking/query/dao"
	"insighttracking/query/model"
	"net/http"

	"insighttracking/apps/admin/internal/svc"
	"insighttracking/apps/admin/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
	"os"
)

type CreateCategoryApiLogic struct {
	logx.Logger
	ctx     context.Context
	svcCtx  *svc.ServiceContext
	Request *http.Request
}

func NewCreateCategoryApiLogic(ctx context.Context, svcCtx *svc.ServiceContext, request *http.Request) *CreateCategoryApiLogic {
	hostname, _ := os.Hostname()
	return &CreateCategoryApiLogic{
		Logger: logx.WithContext(ctx).WithCallerSkip(0).WithFields(
			logx.Field("Log_UUID", uuid.New().String()),
			logx.Field("hostname", hostname)),
		ctx:     ctx,
		svcCtx:  svcCtx,
		Request: request,
	}
}

func (l *CreateCategoryApiLogic) CreateCategoryApi(req *types.CreateCategoryReq) (resp string, err error) {
	fmt.Println("尽量了")
	accountType := cast.ToInt64(l.ctx.Value("accountType"))
	if accountType != enum.EnterpriseEnum {
		return "", errors.New("只有企业账号才可以创建分类")
	}
	enterpriseId := cast.ToInt64(l.ctx.Value("enterpriseId"))
	_, err = dao.CategoryEntity.WithContext(l.ctx).Where(
		dao.CategoryEntity.Name.Eq(req.Name),
		dao.CategoryEntity.ParentID.Eq(req.ParentID),
		dao.CategoryEntity.EnterpriseID.Eq(enterpriseId),
	).First()
	if !errors.Is(err, gorm.ErrRecordNotFound) {
		return "", errors.New("分类名称已经存在,不能重复")
	}
	if err = dao.CategoryEntity.WithContext(l.ctx).Create(&model.CategoryEntity{
		EnterpriseID: enterpriseId, // 关联到enterprise表主键id
		Name:         req.Name,     // 分类名称
		Sort:         req.Sort,     // 排序
		Status:       1,            // 状态:1是正常,2是禁用
		Describe:     req.Describe, // 描述
		ParentID:     req.ParentID, // 父节点id
	}); err != nil {
		return "", errors.New("创建失败")
	}
	return "创建成功", nil
}
